#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :chapter08.py
# @Time      :2021/04/09 15:13:26
# @Author    :Raink


import time
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException


app08 = APIRouter()

"""
中间件，见【run.py】

@app.middleware('http')
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

！！！带yeld的依赖的退出本分代码 和后台任务 会在中间件之后运行
"""


"""
跨域资源共享
域  由 协议、域名、端口  组成，三者有任意一个不同，则属于不同域
"""

"""
后台任务
请求后立即反应，但实际上后台要处理很多任务
比如注册后发邮件
"""

from fastapi import BackgroundTasks

def bg_task(framework: str):
    time.sleep(5)
    with open("README.md", mode="a") as f:
        f.write(f"## {framework}")

@app08.post("/background_tasks")
async def run_bg_tasks(framework: str, back_ground_task: BackgroundTasks):
    # framework 后台任务函数的参数
    back_ground_task.add_task(bg_task, framework)
    return {"message": "任务已经在后台运行"}

"""使用FastAPI的依赖注入系统来导入后台任务"""

def continue_write_readme(background_tasks: BackgroundTasks, q: Optional[str]=None):
    if q:
        background_tasks.add_task(bg_task, "你好你好")
    return q

@app08.post("/dependency/background_tasks")
async def dependency_run_bg_tasks(q: str = Depends(continue_write_readme)):
    if q:
        return {"message": "README.md更新成功"}
